<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
namespace common\behavior;

use Webman\Stomp\Client;

/**
 * 行为扩展：每日报表推送
 */
class EverydayReportPushBehavior
{

    /**
     * @param $params
     * @return void
     */
    public function run(&$params)
    {
        $jsonData = json_decode($params['json'] ?? "{}", true);

        if (empty($jsonData['every_report_push_config'])) {
            return;
        }
        $everyReportPushConfig = $jsonData['every_report_push_config'];
        if (empty($everyReportPushConfig['is_open_everyday_push']) || $everyReportPushConfig['is_open_everyday_push'] != 'yes') {
            return;
        }

        $startTime = strtotime(date('Y-m-d'), time());
        $endTime = strtotime(date('Y-m-d 23:59:59'), time());

        $data['is_every_push'] = true; // 每日推送
        $data['everyday_push_hour'] = $everyReportPushConfig['everyday_push_hour'];
        $data['role'] = $everyReportPushConfig['push_role'];
        $data['project_id'] = $params['id'];
        $data['start_time'] = $startTime;
        $data['end_time'] = $endTime;
        $data['everyday_report_time'] = $startTime; // 日报查询时间

        $everydayPushHour = strtotime(date('Y-m-d ' . $everyReportPushConfig['everyday_push_hour'] . ':00', time()));
        $delayTime = $everydayPushHour - time();
        // 定时推送,不是手动推送,如果修改的时间和现在一样,就不推送
        if ($delayTime <= 0) {
            return;
        }
        try {
            trace("everyday report push behavior" . request()->getUnionUserId(), 'DEBUG');
            Client::send('send_every_day_report', build_queue_data_with_xu($data), $delayTime);
        } catch (\Throwable $e) {
            trace(format_exception_info($e), 'ERR');
        }
    }

}
